package com.socket;
import java.io.*;
import java.net.*;
public class TimeServer {
	static DatagramSocket socket;
	public static void main(String[] args) {
		try {
			socket = new DatagramSocket(7654);			
		}catch (SocketException e) {
			System.err.println("Unable to create socket");
			e.printStackTrace();
			System.exit(1);
		}
		DatagramPacket datagram;
		datagram = new DatagramPacket(new byte[1], 1);
		System.out.println("Listening..");
		while (true) {
			try {
				//receive data (under the form datagram) from Client, then assign it into datagram variable ?!
				socket.receive(datagram);
				//send a data to Client
				respond(datagram); //using 'datagram' (has been received from Client) parameter to get 'address' and 'port' of Client
								   //so that Server can send data to Client 
			}catch (IOException e) {
				e.printStackTrace();
			}			
		}		
	}
	static void respond(DatagramPacket request) {
		ByteArrayOutputStream bs;
		bs = new ByteArrayOutputStream();
		DataOutputStream ds = new DataOutputStream(bs);
		try {
			ds.writeLong(System.currentTimeMillis());			
		}catch (IOException e) {
			
		}
		//-----
		DatagramPacket response;
		byte[] data = bs.toByteArray();
		response = new DatagramPacket(data, data.length, request.getAddress(), request.getPort());
		try {
			socket.send(response);
		}catch (IOException e) {
		}
		//-----
	}
}
